package com.lifang.imsoa.im.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.glassfish.jersey.client.JerseyWebTarget;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.lifang.imsoa.dao.miles.read.CusGuestReadMapper;
import com.lifang.imsoa.dao.miles.read.FytUserReadMapper;
import com.lifang.imsoa.dao.miles.read.LfEmployeeReadMapper;
import com.lifang.imsoa.dao.miles.write.HxChatMsgWriteMapper;
import com.lifang.imsoa.entity.miles.CusGuest;
import com.lifang.imsoa.entity.miles.FytUser;
import com.lifang.imsoa.entity.miles.LfEmployee;
import com.lifang.imsoa.im.comm.Constants;
import com.lifang.imsoa.im.comm.HTTPMethod;
import com.lifang.imsoa.im.comm.RegexUtils;
import com.lifang.imsoa.im.utils.JerseyUtils;
import com.lifang.imsoa.im.vo.EndPoints;
import com.lifang.imsoa.model.ChatMessage;
import com.lifang.imsoa.model.HxChatMsg;
import com.lifang.imsoa.model.MsgContent;
import com.lifang.imsoa.model.MsgEntity;
import com.lifang.json.FasterJsonTool;


@Slf4j
@Service
public class EasemobChatMessage {
	private static JsonNodeFactory factory = new JsonNodeFactory(false);

    @Autowired
    private HxChatMsgWriteMapper hxChatMsgWriteMapper;
    @Autowired
    private FytUserReadMapper fytUserReadMapper;
    @Autowired
    private LfEmployeeReadMapper lfEmployeeReadMapper;
    @Autowired
    private CusGuestReadMapper cusGuestReadMapper;
    
    @Transactional
    public int getChatMsg(Date start,Date end,boolean isInsert){
		ObjectNode queryStrNode = factory.objectNode();
    	queryStrNode.put("ql", "select+*+where+timestamp>="+start.getTime()+"+and+timestamp<"+end.getTime());
        queryStrNode.put("limit", "20");
        int sumCount = 0;//总条数
        Map<String,Object> map = insertMsg(queryStrNode,isInsert);
        Object cursor = map.get("cursor");
        sumCount += Integer.parseInt(map.get("count").toString());
        log.info("<======第1次拉取");
        
        ObjectNode queryStrNode2 = null;
        int sum = 1;
        while(cursor!=null && StringUtils.isNotBlank(cursor.toString())){
        	queryStrNode2 = factory.objectNode();
        	queryStrNode2.put("limit", "20");
        	queryStrNode2.put("cursor", cursor.toString());
        	map = insertMsg(queryStrNode2,isInsert);
        	cursor = map.get("cursor");
        	sum++;
        	log.info("<======第{}次拉取",sum);
        	sumCount += Integer.parseInt(map.get("count").toString());
        }
        log.info("执行完毕,总页数={},下载消息总条数={}",sum,sumCount);
        return sumCount;
    }
    
    public Map<String,Object> insertMsg(ObjectNode queryStrNode,boolean isInsert){
    	ObjectNode messages = getChatMessages(queryStrNode);
    	ChatMessage chatMessage = FasterJsonTool.readValue(messages.toString(), ChatMessage.class);
    	Map<String, Object> map = new HashMap<String, Object>();
    	if(isInsert && chatMessage!=null && CollectionUtils.isNotEmpty(chatMessage.getEntities())){
	    	HxChatMsg hxChatMsg = null;
	        for(MsgEntity msgEntity:chatMessage.getEntities()){
				hxChatMsg = new HxChatMsg();
				hxChatMsg.setMsgId(msgEntity.getMsg_id());
				hxChatMsg.setMsgTime(msgEntity.getTimestamp());
	        	hxChatMsg.setFromUserId(msgEntity.getFrom());
	        	hxChatMsg.setToUserId(msgEntity.getTo());
	        	hxChatMsg.setFromUserName(getRealNameByHxId(msgEntity.getFrom()));
	        	hxChatMsg.setToUserName(getRealNameByHxId(msgEntity.getTo()));
	        	List<MsgContent> msgs = msgEntity.getPayload().getBodies();
	        	if(msgs.size()==1){
	        		hxChatMsg.setMsgContent(msgs.get(0).getMsg());
	        	}else{
	        		log.info("消息条数error,size={}",msgs.size());
	        	}
	        	Object obj = msgEntity.getPayload().getExt();
	        	hxChatMsg.setExt(obj==null?"":obj.toString());
	        	hxChatMsgWriteMapper.insertSelective(hxChatMsg);
	        }
    	}
    	map.put("cursor", chatMessage.getCursor());
    	map.put("count", chatMessage.getEntities().size());
        return map;
    }
    
    /**
     * 根据环信ID获得对应用户姓名
     */
    public String getRealNameByHxId(String hxId){
    	String realName = "--";
    	if("admin".equalsIgnoreCase(hxId)){
    		realName = hxId;
    	}else{
	    	int userId = Integer.parseInt(hxId.substring(4));
	    	if(hxId.contains("jrsp")){
	    		FytUser user = fytUserReadMapper.selectByPrimaryKey(userId);
				if(user!=null && StringUtils.isNotBlank(user.getRealName())){
					realName = user.getRealName();
				}
	    	}else if(hxId.contains("yfyk")){
	    		LfEmployee user = lfEmployeeReadMapper.selectByPrimaryKey(userId);
	    		if(user!=null && StringUtils.isNotBlank(user.getName())){
	    			realName = user.getName();
	    		}
	    	}else if(hxId.contains("wkzf")){
	    		CusGuest cusGuest = cusGuestReadMapper.selectByPrimaryKey(userId);
	    		if(cusGuest!=null && StringUtils.isNotBlank(cusGuest.getName())){
	    			realName = cusGuest.getName();
	    		}
	    	}
    	}
    	return realName;
    }
    
    /**
     * Main Test
     *
     * @param args
     */
    public static void main(String[] args) {
    	
    	

        /**
         *  聊天消息 获取最新的20条记录
         */
//        ObjectNode queryStrNode = factory.objectNode();
//        queryStrNode.put("ql", "select+*+where+from='jrsp19'+and+to='jrsp48'");
//        queryStrNode.put("limit", "20");
//        ObjectNode messages = getChatMessages(queryStrNode);
//        System.out.println(messages);
        
        /**
         *  聊天消息 获取7天以内的消息
         */
    	/*
        String currentTimestamp = String.valueOf(System.currentTimeMillis());
        String senvenDayAgo = String.valueOf(System.currentTimeMillis() - 7 * 24 * 60 * 60 * 1000);
        ObjectNode queryStrNode1 = factory.objectNode();
        queryStrNode1.put("ql", "select * where timestamp>" + senvenDayAgo + " and timestamp<" + currentTimestamp);
        ObjectNode messages1 = getChatMessages(queryStrNode1);
		System.out.println(messages1);
    	*/
    	
        /**
         *  聊天消息 分页获取
         */
    	
    	
//        ObjectNode queryStrNode2 = factory.objectNode();
//        queryStrNode2.put("limit", "10");
//        // 第一页
//        ObjectNode messages2 = getChatMessages(queryStrNode2);
//        System.out.println(messages2);
//        // 第二页
//        String cursor = messages2.get("cursor").asText();
//        queryStrNode2.put("cursor", cursor);
//        ObjectNode messages3 = getChatMessages(queryStrNode2);
//        System.out.println(messages3);
    }

    /**
	 * 获取聊天消息
	 * 
	 * @param queryStrNode
	 *
	 */
	public static ObjectNode getChatMessages(ObjectNode queryStrNode) {
		ObjectNode objectNode = factory.objectNode();
		// check appKey format
		if (!RegexUtils.match("^(?!-)[0-9a-zA-Z\\-]+#[0-9a-zA-Z]+", Constants.JRSP_APPKEY)) {
			log.error("Bad format of Appkey: " + Constants.JRSP_APPKEY);
			objectNode.put("message", "Bad format of Appkey");
			return objectNode;
		}
		try {
			JerseyWebTarget webTarget = EndPoints.CHATMESSAGES_TARGET.resolveTemplate("org_name", Constants.JRSP_APPKEY.split("#")[0])
					.resolveTemplate("app_name", Constants.JRSP_APPKEY.split("#")[1]);
			if (null != queryStrNode && null != queryStrNode.get("ql") && !StringUtils.isEmpty(queryStrNode.get("ql").asText())) {
				webTarget = webTarget.queryParam("ql", queryStrNode.get("ql").asText());
			}
			if (null != queryStrNode && null != queryStrNode.get("limit") &&!StringUtils.isEmpty(queryStrNode.get("limit").asText())) {
				webTarget = webTarget.queryParam("limit", queryStrNode.get("limit").asText());
			}
			if (null != queryStrNode && null != queryStrNode.get("cursor") &&!StringUtils.isEmpty(queryStrNode.get("cursor").asText())) {
				webTarget = webTarget.queryParam("cursor", queryStrNode.get("cursor").asText());
			}
			objectNode = JerseyUtils.sendRequest(webTarget, null, Constants.jrsp_credential, HTTPMethod.METHOD_GET, null);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return objectNode;
	}
}
